<html lang="en">
	<head>
		<title>three.js - webgpu - tsl transpiler</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">
	</head>
	<body>

		<style>
			#source {
				position: absolute;
				top: 0;
				left: 0;
				width: 50%;
				height: 100%;
			}
			#result {
				position: absolute;
				top: 0;
				right: 0;
				width: 50%;
				height: 100%;
			}
		</style>

		<div id="source"></div>
		<div id="result"></div>
		<script src="https://cdn.jsdelivr.net/npm/monaco-editor@latest/min/vs/loader.min.js"></script>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.webgpu.js",
					"three/tsl": "../build/three.webgpu.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import Transpiler from 'three/addons/transpiler/Transpiler.js';
			import GLSLDecoder from 'three/addons/transpiler/GLSLDecoder.js';
			import TSLEncoder from 'three/addons/transpiler/TSLEncoder.js';

			init();

			function init() {

				// editor

				window.require.config( { paths: { 'vs': 'https://cdn.jsdelivr.net/npm/monaco-editor@0.48.0/min/vs' } } );

				require( [ 'vs/editor/editor.main' ], () => {

					let timeout = null;

					const editorDOM = document.getElementById( 'source' );
					const resultDOM = document.getElementById( 'result' );

					const glslCode = `// Put here your GLSL code to transpile to TSL:

float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {

	float a2 = pow2( alpha );

	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );

	return 0.5 / max( gv + gl, EPSILON );

}
`;

					const editor = window.monaco.editor.create( editorDOM, {
						value: glslCode,
						language: 'glsl',
						theme: 'vs-dark',
						automaticLayout: true,
						minimap: { enabled: false }
					} );

					const result = window.monaco.editor.create( resultDOM, {
						value: '',
						language: 'javascript',
						theme: 'vs-dark',
						automaticLayout: true,
						readOnly: true,
						minimap: { enabled: false }
					} );

					const showCode = ( code ) => {

						result.setValue( code );
						result.revealLine( 1 );

					};

					const build = () => {

						try {

							const glsl = editor.getValue();

							const decoder = new GLSLDecoder();
							const encoder = new TSLEncoder();

							const transpiler = new Transpiler( decoder, encoder );
							const tsl = transpiler.parse( glsl );

							showCode( tsl );

						} catch ( e ) {

							result.setValue( 'Error: ' + e.message );

						}

					};

					build();

					editor.getModel().onDidChangeContent( () => {

						if ( timeout ) clearTimeout( timeout );

						timeout = setTimeout( build, 1000 );

					} );

				} );

			}

		</script>
	</body>
</html>
